<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage" :left="240">
    <template #left>
      <l-panel :title="$t('接口分类')" style="padding-right: 0">
        <el-tree
          ref="mytree"
          v-loading="treeLoading"
          node-key="value"
          default-expand-all
          :expand-on-click-node="false"
          :data="apiArr"
          :props="defaultProps"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="fa fa-sitemap"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入关键字查询')"
            v-model="searchWord"
            @keyup.enter.native="hanleSearch"
            size="mini"
          >
            <el-button slot="append" icon="el-icon-search" @click="hanleSearch"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableShowData"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <template v-slot:f_Description="scope">
          <!--{{scope.row.f_TenantType==0 ?"普通租户":"系统平台租户"}}-->
          <el-button type="text" @click.native="repostShowForm(scope.$index, scope.row)" v-if="!scope.row.f_FileId"
            >创建报表</el-button
          >
          <el-button type="text" @click.native="repostOpenedForm(scope.$index, scope.row)" v-if="scope.row.f_FileId"
            >编辑报表</el-button
          >
          <el-button
            type="text"
            @click.native="repostViewForm(scope.$index, scope.row)"
            v-if="scope.row.f_FileId"
            style="color: #67c23a"
            >报表预览</el-button
          >
          <el-upload
            ref="upload"
            action="#"
            :limit="1"
            :show-file-list="false"
            :http-request="httpRequest"
            :data="{ reportid: scope.row.f_Id }"
            style="display: inline-block; margin-left: 10px"
            v-if="!scope.row.f_FileId && uploadState"
          >
            <el-button type="text" style="color: #67c23a">上传报表</el-button>
          </el-upload>
        </template>

        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
      :width="600"
    >
      <my-form ref="form"></my-form>
    </l-dialog>

    <el-dialog class="ui-report-pop" :title="repostTitle" :visible.sync="repostVisible" :fullscreen="true">
      <Stimulsoft ref="repostForm" @repostSave="repostSaveForm"></Stimulsoft>
    </el-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.report.reportinfo;
const api2 = window.$api.report.reportcategory;
import MyForm from "./form";
import Stimulsoft from "./stimulsoft";
export default {
  components: {
    MyForm,
    Stimulsoft,
  },
  data() {
    return {
      lr_isPage: true,
      // 表格
      columns: [
        { label: "报表名称", prop: "f_Name", minWidth: "120" },
        { label: "数据接口", prop: "apiUrl", minWidth: "240" },
        { label: "报表操作", prop: "f_Description", minWidth: "120" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "Delete", label: "删除" },
      ],
      tableLoading: false,
      searchWord: "",
      tableShowData: [],
      tableData: [],

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      //分页
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      keyWord: "",

      apiArr: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeLoading: false,
      f_CategoryId: "",

      repostVisible: false,
      repostId: "",
      repostTitle: "创建报表",
      uploadState: true,
    };
  },
  mounted() {
    //var data = await this.$awaitWraper(api2.getTenantList());
    this.$nextTick(() => {
      //this.loadTable();
      var _this = this;
      api2
        .getList()
        .then((res) => {
          res.data.data.forEach(function (v) {
            v.label = v.f_Name;
            v.value = v.f_Id;
          });
          var list = _this.$deepClone(res.data.data);
          //console.log(res.data.data);
          _this.apiArr = this.lr_apiTree(list);
          _this.loadTablePageData();
        })
        .catch(() => {});
    });
  },
  computed: {},
  methods: {
    lr_apiTree(data) {
      data = data || [];
      return this.$toTree(data, "f_Id", "f_ParentId", "f_Id", "f_Name");
    },

    handleNodeClick(node) {
      this.loading = true;
      this.f_CategoryId = node.f_Id;
      this.loadTablePageData();
    },

    loadTablePageData(isNotFirst) {
      if (isNotFirst) {
        this.tableCurrentPage = 1;
        this.searchWord = "";
        this.tableData = [];
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        keyword: this.searchWord,
        f_CategoryId: this.f_CategoryId,
        f_EnabledMark: 1,
      };
      this.tableData = [];
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = this.lr_apiTree(data.rows);
          //console.log(this.tableData);
          this.tableTotal = data.records;
          this.tableShowData = this.tableData;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    hanleSearch() {
      this.loadTablePageData();
    },

    // 表单部分
    handleAdd() {
      this.formEdit = false;
      this.showForm("新增报表");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm("编辑接口信息");
    },
    handleDelete($index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.tableShowData.splice($index, 1);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async handleSave(showLoading, hideLoading) {
      showLoading();
      if (!(await this.$refs.form.validateForm())) {
        hideLoading();
        return;
      }
      const formData = this.$refs.form.getForm();
      if (this.formEdit) {
        // 修改数据
        api
          .update(formData.f_Id, formData)
          .then(() => {
            hideLoading();
            this.formVisible = false;
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.loadTablePageData(true);
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        // 新增数据
        api
          .add(formData)
          .then(() => {
            hideLoading();
            this.formVisible = false;
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.loadTablePageData(true);
          })
          .catch(() => {
            hideLoading();
          });
      }
    },
    handleOpenedForm() {
      if (this.formEdit) {
        this.$refs.form.setForm(this.formEditRow);
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    //报表数据源
    repostApiData(row, callback) {
      var _this = this;
      api.getApi(row.f_InterfaceId).then((res) => {
        var data = res.data.data;
        var Param = {};
        if (row.f_EnCode == 0) {
          var arr = JSON.parse(data.f_RequestParameters);
          arr.forEach(function (v) {
            Param[v.name] = v.value;
          });
        } else if (row.f_EnCode == 2) {
          Param = JSON.parse(data.f_RequestParameters);
        }
        api
          .request(data.f_Url, data.f_RequestMethod, Param)
          .then((res) => {
            var data = res.data.data.rows || res.data.data;
            if (typeof callback == "function") callback(data);
          })
          .catch(() => {
            _this.$message({
              type: "warning",
              message: "获取数据源失败!",
            });
          });
      });
    },

    //创建报表
    repostShowForm(index, row) {
      var _this = this;
      _this.repostTitle = "创建报表";
      _this.repostApiData(row, function (data) {
        _this.repostVisible = true;
        _this.$nextTick(function () {
          _this.$refs.repostForm.init(data, row);
        });
      });
    },
    //编辑报表
    repostOpenedForm(index, row) {
      var _this = this;
      _this.repostTitle = "编辑报表";
      _this.repostApiData(row, function (data) {
        api
          .getreporturl({ id: row.f_FileId })
          .then((res) => {
            _this.repostVisible = true;
            var url = res.data.data; //报名路径
            _this.$nextTick(function () {
              _this.$refs.repostForm.setForm(data, row, url);
            });
          })
          .catch(() => {
            _this.$message({
              type: "warning",
              message: "获取报表地址失败!",
            });
          });
      });
    },
    //报表预览
    repostViewForm(index, row) {
      var _this = this;
      _this.repostTitle = "报表预览";
      _this.repostApiData(row, function (data) {
        api.getreporturl({ id: row.f_FileId }).then((res) => {
          _this.repostVisible = true;
          var url = res.data.data; //报名路径
          _this.$nextTick(function () {
            _this.$refs.repostForm.viewForm(data, row, url);
          });
        });
      });
    },
    //报表保存
    repostSaveForm(data) {
      api
        .uploadreportfile({ file: this.encode(data.jsonStr), reportid: data.reportid })
        .then(() => {
          this.$message({
            type: "success",
            message: "保存成功!",
          });
          this.repostVisible = false;
          this.loadTablePageData(true);
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "保存失败!",
          });
        });
    },

    //报表上传
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          fileResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
    httpRequest(data) {
      //this.$refs.upload.clearFiles();
      this.uploadState = false;
      if (data.file.name.toLowerCase().indexOf(".mrt") == -1) {
        this.$message({
          type: "warning",
          message: "请上传mrt报表文件",
        });
        this.$nextTick(function () {
          this.uploadState = true;
        });
      } else {
        this.getBase64(data.file).then((resBase64) => {
          this.fileBase64 = resBase64.split(",")[1];
          data.data.file = resBase64.split(",")[1];
          api
            .uploadreportfile(data.data)
            .then(() => {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.loadTablePageData(true);
            })
            .catch(() => {
              this.$message({
                type: "warning",
                message: "添加失败!",
              });
              this.$nextTick(function () {
                this.uploadState = true;
              });
            });
        });
      }
    },
    //表单关闭
    repostHideForm() {
      this.repostVisible = false;
    },
    encode(str) {
      // 对字符串进行编码
      var encode = encodeURIComponent(str);
      // 对编码的字符串转化base64
      var base64 = btoa(encode);
      return base64;
    },
  },
};
</script>
<style>
.ui-report-pop .el-dialog__body {
  padding: 0;
}
</style>
